package com.tool;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.sql.SQLException;
import java.util.List;

import static com.tool.dbTest.hexStringToByte;

/**
 * Created by Administrator on 2018-9-14.
 */
public class UDPClient {
    private DatagramSocket socket;

    /*
     * 客户端的启动
     */
    public void start(List<String> cmdList) {
        try {
            socket = new DatagramSocket();
            String str = "你好！服务端！";
          //  byte[] data = str.getBytes("UTF-8");
            //打包：准备包裹，填写地址，装入数据
            InetAddress address = InetAddress.getByName("10.100.2.75");
            int port = 10018;

            for (String item:cmdList) {
                byte[] data=hexStringToByte(item);
                //创建发送包
                DatagramPacket sendPacket = new
                        DatagramPacket(data, data.length, address, port);

                //将其发送出去
                socket.send(sendPacket);
            }


            //接收
            byte[] recvBuf = new byte[100];
            DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length);
            socket.receive(recvPacket);

            String str2 =bytesToHexString(recvPacket.getData());
            System.out.println("服务端说:" + str2);
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        db mysqltest = new db();

        List<String> hiscmd= null;
        try {
            hiscmd = mysqltest.querycmd("select * from roadhis where deviceid='64708302743'",true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        int i=0;
        for (String item:hiscmd
                ) {
            System.out.println(item);
        }
        UDPClient client = new UDPClient();
        client.start(hiscmd);

    }

    public static  String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }
}
